# Name: JoinGaezGrid.py - MCBS 10/08/2014
# Description: Joins FAO GAEZ data info to grid. 

# import system module
import arcpy
from arcpy import env
from arcpy.sa import *

# Set workspace environment:
#env.workspace = "Rasters.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Rasters.gdb"
env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridCoarseName      = "G5kmMiRWGS"
GridCoarseCellName  = GridCoarseName + "Cell"
FinalGridName       = "G1kmMiRWGS"
GridMatchFeat       = "G1kmG5kmWGS"
GridCoarseFID       = "G5kmMiR_FID"

FieldsGridMatch   = arcpy.FieldMappings()
FieldsGridMatch.addTable(GridCoarseCellName)
x = FieldsGridMatch.findFieldMapIndex("Join_Count")
FieldsGridMatch.removeFieldMap(x)

FieldsGridMatch.addTable(FinalGridName)
x = FieldsGridMatch.findFieldMapIndex("Join_Count")
FieldsGridMatch.removeFieldMap(x)

print " Creating match between coarse and thin grids ..."
# Create Match between coarse grid and final grid:
arcpy.SpatialJoin_analysis(FinalGridName, GridCoarseCellName, GridMatchFeat, "#", "#", FieldsGridMatch)

# Delete unused fields from GridMatchFeat
arcpy.DeleteField_management(GridMatchFeat, ["TARGET_FID","TARGET_FID_1","Join_Count","Shape_Area_1","Shape_Length_1"])

Crops = ["mze","soy","suc"]
Datasets = ["aclim_","aecol_","act_"]
GB = "gaez_"

# initialize lists:
ListToExtract = []
ListToMatch   = []

for d in Datasets:
	for c in Crops:
		Raster = GB + d + c
		ListToExtract.append( [Raster, Raster] )
		ListToMatch.append( Raster )
			
GridGaezName = 	GridCoarseName + "GAEZ"
arcpy.CopyFeatures_management(GridCoarseName, GridGaezName)
ExtractMultiValuesToPoints(GridGaezName,ListToExtract, "NONE")

GridMatchGaez = GridMatchFeat + "GAEZ"
arcpy.CopyFeatures_management(GridMatchFeat, GridMatchGaez)
arcpy.JoinField_management(GridMatchGaez, GridCoarseFID, GridGaezName, GridCoarseFID, ListToMatch)

print " Writing table ... "
TableGaezName    = GridMatchGaez + ".dbf"
arcpy.TableToTable_conversion(GridMatchGaez, PathForTables, TableGaezName)
print TableGaezName + " written."


# Do it for slope and altitude...	
# NewAltitudeName = "Altitude"
# NewSlopeName    = "Slope"
# arcpy.CopyRaster_management("altPrj_33",NewAltitudeName)
# arcpy.Mosaic_management("altPrj_34",NewAltitudeName,"","", "", "", "", "", "NONE")
# outSlope = Slope(NewAltitudeName, "DEGREE")
# outSlope.save(NewSlopeName)
